package juntos.lbcv.thread;

import java.util.List;
import java.util.Set;

import juntos.lbcv.dao.AlertDAO;
import juntos.lbcv.model.Alert;
import juntos.lbcv.model.AlertAnnonce;
import juntos.lbcv.model.Annonce;
import juntos.lbcv.model.UserAlert;
import juntos.lbcv.utils.Lbc;
import juntos.lbcv.utils.SendHtmlEmail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Component
@Scope("prototype")
public class SendingAlertTask implements Runnable  {

	@Autowired
	AlertDAO alertDAO;
	
	private boolean sendAlert = true;

	
	public void sendAlertAnnonceForEachUser() {
		alertDAO.beginTransaction();
		List<UserAlert> userAlerts = alertDAO.findAllUserAlert();
		for(UserAlert userAlert:userAlerts){
			Lbc.printOut("*** User : "+userAlert.getNom()+" ********");
			Set<Alert> alerts = userAlert.getAlerts();
			for(Alert alert: alerts){
				Lbc.printOut("********* Alert : "+alert.getTitre()+" ********");
				 List<AlertAnnonce> alertAnnonces = alertDAO.findAllAlertAnnoncesByAlertAndStatut(alert);
				 String html = "";
				 for(AlertAnnonce an: alertAnnonces){
					Annonce annonce = an.getAnnonce();
					Lbc.printOut("***************** Annonce : "+annonce.getIdleboncoin()+" - "+annonce.getTitre()+" ********");
					html +="<br>"+Lbc.getAnnonceHtml(annonce);
					an.setStatut(1);
				}
				if(!"".equals(html)){
					SendHtmlEmail.run(userAlert.getEmail(), ""+alert.getTitre(), html);
				}
			}
		}
		alertDAO.commit();
		
	}

	@Override
	public void run() {
	
		while(sendAlert){
			this.sendAlertAnnonceForEachUser();
			Lbc.waitXSecondes(300);
		}
	}
	

}
